package com.lrj.wc;


import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 有界流wc
 *
 * @author lrj
 * @date 2022/3/18 14:36
 */
public class BoundedStreamWordCount {
    public static void main(String[] args) throws Exception {
        // org.apache.flink.streaming.api.environment
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = env.readTextFile("input/wc/word.txt")
                .flatMap((String s, Collector<Tuple2<String, Long>> c) -> {
                    for (String str : s.split("\\s+")) {
                        c.collect(new Tuple2<>(str, 1L));
                    }
                }).returns(Types.TUPLE(Types.STRING, Types.LONG))
                .keyBy(t -> t.f0)
                .sum(1);

        /*
            5> (world,1)
            3> (hello,1)
            2> (java,1)
            3> (hello,2)
            3> (hello,3)
            7> (flink,1)
            <threadId>> out
            slot插槽概念
            并行子任务数目=并行度
            分组将相同key交给同一个子任务去处理,分区处理
            并不是按顺序打印的,分布式执行环境,多线程模拟flink并行执行
        * */
        sum.print();
        env.execute(BoundedStreamWordCount.class.getName());
    }
}
